package problem529;

//529.扫雷游戏
//https://leetcode.cn/problems/minesweeper/

class Solution {
    int n,m;
    int[] xx = {1,-1,0, 0,-1,1, 1,-1};
    int[] yy = {0, 0,1,-1, 1,1,-1,-1};
    public char[][] updateBoard(char[][] board, int[] click) {
        n = board.length;
        m = board[0].length;

        int x = click[0], y = click[1];
        if(board[x][y] == 'M') {
            board[x][y] = 'X';
            return board;
        }

        dfs(board, x, y);
        return board;
    }

    public void dfs(char[][] board, int x, int y) {
        int count = 0;
        for(int i = 0; i<8; i++) {
            int dx = x + xx[i];
            int dy = y + yy[i];
            //统计周围雷的个数
            if(dx >= 0 && dx < n && dy >= 0 && dy < m && board[dx][dy] == 'M') {
                count++;
            }
        }
        if(count != 0) {
            board[x][y] = (char)('0' + count);
        }else {
            board[x][y] = 'B';
            for(int i = 0; i<8; i++) {
                int dx = x + xx[i];
                int dy = y + yy[i];
                if(dx >= 0 && dx < n && dy >= 0 && dy < m && board[dx][dy] != 'M' && board[dx][dy] == 'E') {
                    dfs(board, dx, dy);
                }
            }
        }
    }
}